const mysql = require('mysql'); // mysql模块
const { v4: uuid } = require('uuid'); // UUID

const publicDao = require('dao/public-dao');
const flashDao = require('dao/flash-dao');

const tableName = 'flash'; // 表格名称
const service = {};

/**
 * 分页列表
 * @param {Object} params 参数
 * @param {Function} callback 回调
 */
service.getPageList = (params, callback) => {
  // 查询条件
  let whereStr = '';
      whereStr += params.title ? 'title LIKE ' + mysql.escape('%' + params.title + '%') + ' AND ' : '';
      whereStr += params.type ? 'type=' + mysql.escape(params.type) + ' AND ' : '';
      whereStr += params.enable_state !== '' ? 'enable_state=' + mysql.escape(params.enable_state) + ' AND ' : '';
      whereStr += params.audit_state ? 'audit_state=' + mysql.escape(params.audit_state) + ' AND ' : '';
  if (whereStr !== '') {
    whereStr = ' WHERE ' + whereStr.slice(0, whereStr.length - 5);
  }
  // 排序条件
  let orderByStr = ' ORDER BY update_time,hits';
  // dao
  publicDao.getPageList(tableName, params, whereStr, orderByStr, callback);
}

/**
 * 详情
 * @param {String} id
 * @param {Function} callback 回调
 */
service.detail = (id, callback) => {
  flashDao.detail(id, callback);
}

/**
 * 新增
 * @param {Object} params 参数
 * @param {Function} callback 回调
 */
service.add = (params, callback) => {
  // 设置默认值
  params.id = uuid(); // 生成UUID
  params.update_time = new Date(); // 修改时间
  params.user_name = 'Bell'; // 上传者默认
  // 设置审核时间和状态，暂时不审核，等开通用户上传通道后删除审核代码
  params.audit_time = new Date();
  params.audit_state = 2;
  // dao
  publicDao.add(tableName, params, callback);
}

/**
 * 修改
 * @param {Object} params 参数
 * @param {Function} callback 回调
 */
service.update = (params, callback) => {
  publicDao.update(tableName, params, callback);
}

/**
 * 删除
 * @param {Array} ids id列表
 * @param {Function} callback 回调
 */
service.remove = (ids, callback) => {
  publicDao.remove(tableName, ids, callback);
}

module.exports = service;
